from django.core.urlresolvers import reverse
from django.db.models.loading import get_model
from django.db.models.query import QuerySet
from django.http import Http404
from django.shortcuts import get_object_or_404

from tppt.lib import exceptions
from tppt.lib.db import filters

def get_object_specification(object):
	from tppt.lib import Model
	params={}
	if isinstance(object, Model):
		params['entity_key']=object.pk
		params['entity_model_name']=object.__class__.__name__
	elif isinstance(object, QuerySet):
		params['model_name']=object.model.__name__
		filter_spec=filters.get_filter_spec(object)
		if filter_spec:
			params['model_filter']=filter_spec
			
	else:
		raise exceptions.ArgumentError('Trying to get action URL for unsupported object.')
	return params

def get_object_from_specification(spec):
	
	if 'entity_model_name' in spec and 'entity_key' in spec:
		model=get_model('data', spec['entity_model_name'])
		if not model:
			raise exceptions.MissingModelError(spec['entity_model_name'])
		return get_object_or_404(model, pk=spec['entity_key'])
	if 'model_name' in spec:
		model=get_model('data', spec['model_name'])
		if not model:
			raise exceptions.MissingModelError(spec['model_name'])
		query_set=model.objects.all()
		if 'model_filter' in spec:
			query_set=filters.apply_filter_spec(query_set, spec['model_filter'])
		return query_set
	return None
	


def get_action_url(action, object=None, model=None, key=None, user_params={}):

	if isinstance(action, str):
		action_name=action
		action_object=None
	else:
		action_name=action.get_name()
		action_object=action
	if model:
		if not isinstance(model, str):
			model=model.__name__

	if object:
		params=get_object_specification(object)
	elif model and key:
		params={'entity_model_name': model_name, 'entity_key': key}
	elif model:
		params={'model_name': model}
	else:
		params={}
		
	params['action_name']=action_name
	if action_object:
		params.update(action_object.get_nondefault_params())
	
	params.update(user_params)
	
	url=reverse('tppt.lib.views.perform_action', kwargs=params)
	
	del params['action_name']
	
	if len(params)>0:
		from urllib import urlencode
		url+=urlencode(params)
	return url 
